package stackoverflow.data.repositoryimpl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import stackoverflow.domain.question.Question;
import stackoverflow.domain.question.QuestionRepository;

@Repository("questionRepositoryImpl")
public class QuestionRepositoryImpl extends HibernateRepository implements
		QuestionRepository {
	
	@Autowired
	public QuestionRepositoryImpl(
			@Qualifier("sessionFactory")SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@SuppressWarnings("unchecked")
	@Transactional(propagation=Propagation.REQUIRED)
	public List<Question> findAll() {
		String hql = "from Question";
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery(hql);
		
		return query.list();
	}

	@Transactional
	public void add(Question question) {
		Session session = sessionFactory.getCurrentSession();
		session.save(question); 
	}

	public Question findQuestionById(String questionId) {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.getNamedQuery("findQuestionById");
		query.setString("id", questionId);
		return (Question) query.uniqueResult(); // returns null if no results
	}
}
